import moment from 'moment/moment'
import {accessRecordsDB} from './lowdb.ts'
import {AccessRecord} from '@/data/Dream'

export function recordMovieAccessRecords(movieRecordsKey: string) {
    return recordAccessRecords('movieAccessRecords', movieRecordsKey)
}

export function recordVideoAccessRecords(videoFileName: string) {
    return recordAccessRecords('videoAccessRecords', videoFileName)
}

function recordAccessRecords(recordsName: string, recordsKey: string) {
    const records = accessRecordsDB.get(recordsName).value()

    const ctime = moment().format('YYYY-MM-DD HH:mm:ss')

    let thisRecord: AccessRecord = records[recordsKey]
    if (!thisRecord) {
        thisRecord  = {
            accessCount: 1,
            lastAccessTime: ctime
        }
        records[recordsKey] = thisRecord
    } else {
        thisRecord.accessCount++
        thisRecord.lastAccessTime = ctime
    }

    accessRecordsDB.write()

    console.log(recordsKey, thisRecord)
    return thisRecord
}

export function sortByAccessRecords(aRecords: AccessRecord, bRecords: AccessRecord) {
    let bCount = bRecords?.accessCount ?? 0
    let aCount = aRecords?.accessCount ?? 0
    const sort = bCount - aCount
    if (sort === 0) {
        let bTime = bRecords?.lastAccessTime ?? '0'
        let aTime = aRecords?.lastAccessTime ?? '0'
        return bTime.localeCompare(aTime)
    }
    return sort
}

export function sortByLastAccessTime(aRecords: AccessRecord, bRecords: AccessRecord) {
    let bTime = bRecords?.lastAccessTime ?? '0'
    let aTime = aRecords?.lastAccessTime ?? '0'
    return bTime.localeCompare(aTime)
}
